package com.ease.script.ognl;

import java.util.Map;

import ognl.NullHandler;
import ognl.Ognl;
import ognl.OgnlRuntime;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author nathanleewei
 * 
 */
public abstract class OgnlUtil {

	private static final transient Log log = LogFactory.getLog(OgnlUtil.class);

	/**
	 * 非多线程安全
	 * 
	 * @param root
	 * @param parameters
	 * @throws Exception
	 */
	public static synchronized void setParameters(Object root, final Map<String, ?> parameters) {
		NullHandler nullHandler = null;
		try {
			nullHandler = OgnlRuntime.getNullHandler(Object.class);
			OgnlNullHandler ognlNullHandler = new OgnlNullHandler();
			OgnlRuntime.setNullHandler(Object.class, ognlNullHandler);
			for (Map.Entry<String, ?> entry : parameters.entrySet()) {
				String name = entry.getKey();
				Object value = entry.getValue();
				try {
					Ognl.setValue(name, root, value);
				} catch (Throwable e) {
					log.warn("Ognl.setValue: name=" + name + ", value=" + value);
				}
			}
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			OgnlRuntime.setNullHandler(Object.class, nullHandler);
		}
	}
}
